// 书签功能JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const bookmarksContainer = document.getElementById('bookmarks-container');
    const categoriesContainer = document.getElementById('categories-container');
    const loadingIndicator = document.getElementById('loading-indicator');
    const noBookmarksMessage = document.getElementById('no-bookmarks');
    const searchInput = document.getElementById('search-input');
    const searchType = document.getElementById('search-type');
    const searchBtn = document.getElementById('search-btn');
    
    // 模态框元素
    const bookmarkModal = new bootstrap.Modal(document.getElementById('bookmark-modal'));
    const categoryModal = new bootstrap.Modal(document.getElementById('category-modal'));
    const descriptionModal = new bootstrap.Modal(document.getElementById('description-modal'));
    
    // 表单元素
    const bookmarkForm = document.getElementById('bookmark-form');
    const bookmarkId = document.getElementById('bookmark-id');
    const bookmarkTitle = document.getElementById('bookmark-title');
    const bookmarkUrl = document.getElementById('bookmark-url');
    const bookmarkCategory = document.getElementById('bookmark-category');
    const bookmarkDescription = document.getElementById('bookmark-description');
    const categoryName = document.getElementById('category-name');
    
    // 按钮元素
    const addBookmarkBtn = document.getElementById('add-bookmark-btn');
    const saveBookmarkBtn = document.getElementById('save-bookmark-btn');
    const addCategoryBtn = document.getElementById('add-category-btn');
    const saveCategoryBtn = document.getElementById('save-category-btn');
    
    // 描述模态框元素
    const descriptionTitle = document.getElementById('description-title');
    const descriptionContent = document.getElementById('description-content');
    
    // 存储所有书签和类别
    let allBookmarks = [];
    let allCategories = [];
    
    // 初始化加载
    loadBookmarks();
    loadCategories();
    
    // 事件监听器
    addBookmarkBtn.addEventListener('click', showAddBookmarkModal);
    saveBookmarkBtn.addEventListener('click', saveBookmark);
    addCategoryBtn.addEventListener('click', showAddCategoryModal);
    saveCategoryBtn.addEventListener('click', saveCategory);
    searchBtn.addEventListener('click', searchBookmarks);
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchBookmarks();
        }
    });
    
    // 加载所有书签
    function loadBookmarks() {
        loadingIndicator.style.display = 'block';
        noBookmarksMessage.style.display = 'none';
        
        fetch('/api/bookmarks/all')
            .then(response => response.json())
            .then(data => {
                allBookmarks = data.bookmarks;
                allCategories = data.categories;
                renderBookmarks(allBookmarks);
                loadingIndicator.style.display = 'none';
                
                if (allBookmarks.length === 0) {
                    noBookmarksMessage.style.display = 'block';
                }
            })
            .catch(error => {
                console.error('加载书签失败:', error);
                loadingIndicator.style.display = 'none';
                noBookmarksMessage.style.display = 'block';
                noBookmarksMessage.innerHTML = '<p>加载书签失败，请刷新页面重试</p>';
            });
    }
    
    // 加载所有类别
    function loadCategories() {
        const categoriesLoading = document.getElementById('categories-loading');
        
        fetch('/api/bookmarks/categories')
            .then(response => response.json())
            .then(data => {
                allCategories = data.categories;
                renderCategories();
                updateCategorySelect();
                categoriesLoading.style.display = 'none';
            })
            .catch(error => {
                console.error('加载类别失败:', error);
                categoriesLoading.style.display = 'none';
            });
    }
    
    // 渲染书签列表
    function renderBookmarks(bookmarks) {
        // 清空容器
        bookmarksContainer.innerHTML = '';
        
        if (bookmarks.length === 0) {
            noBookmarksMessage.style.display = 'block';
            return;
        }
        
        noBookmarksMessage.style.display = 'none';
        
        // 按类别分组
        const bookmarksByCategory = {};
        
        bookmarks.forEach(bookmark => {
            if (!bookmarksByCategory[bookmark.category]) {
                bookmarksByCategory[bookmark.category] = [];
            }
            bookmarksByCategory[bookmark.category].push(bookmark);
        });
        
        // 渲染每个类别
        for (const category in bookmarksByCategory) {
            const categoryDiv = document.createElement('div');
            categoryDiv.className = 'bookmark-category mb-3';
            
            // 类别标题
            const categoryHeader = document.createElement('div');
            categoryHeader.className = 'category-header';
            categoryHeader.setAttribute('data-bs-toggle', 'collapse');
            categoryHeader.setAttribute('data-bs-target', `#category-${category.replace(/\s+/g, '-')}`);
            categoryHeader.setAttribute('aria-expanded', 'true');
            
            const categoryTitle = document.createElement('h5');
            categoryTitle.className = 'mb-0 d-flex align-items-center';
            categoryTitle.innerHTML = `
                <span>${category}</span>
                <span class="ms-2 badge bg-secondary">${bookmarksByCategory[category].length}</span>
                <span class="category-toggle-icon ms-2"></span>
            `;
            
            categoryHeader.appendChild(categoryTitle);
            categoryDiv.appendChild(categoryHeader);
            
            // 类别内容
            const categoryContent = document.createElement('div');
            categoryContent.className = 'collapse show';
            categoryContent.id = `category-${category.replace(/\s+/g, '-')}`;
            
            const bookmarksList = document.createElement('div');
            bookmarksList.className = 'category-content';
            
            // 渲染该类别下的所有书签
            bookmarksByCategory[category].forEach(bookmark => {
                const bookmarkItem = document.createElement('div');
                bookmarkItem.className = 'bookmark-item';
                bookmarkItem.setAttribute('data-id', bookmark.id);
                
                // 创建一个包含标题和按钮的容器，确保它们在同一行
                const bookmarkContainer = document.createElement('div');
                bookmarkContainer.className = 'bookmark-container d-flex justify-content-between align-items-center w-100';
                bookmarkItem.appendChild(bookmarkContainer);
                
                const bookmarkInfo = document.createElement('div');
                bookmarkInfo.className = 'bookmark-info';
                
                // 只显示书签标题，不显示URL
                const title = bookmark.title || bookmark.url;
                const bookmarkTitle = document.createElement('div');
                bookmarkTitle.className = 'bookmark-title';
                bookmarkTitle.textContent = title;
                
                // 仍然创建URL元素但不添加到DOM中，保留给描述模态框使用
                const bookmarkUrl = document.createElement('div');
                bookmarkUrl.className = 'bookmark-url';
                bookmarkUrl.textContent = bookmark.url;
                
                bookmarkInfo.appendChild(bookmarkTitle);
                // 移除URL显示逻辑，不再显示URL
                
                // 书签操作按钮 - 确保与标题在同一行
                const bookmarkActions = document.createElement('div');
                bookmarkActions.className = 'bookmark-actions';
                
                // 查看描述按钮 - 无论是否有描述内容都显示
                const viewDescBtn = document.createElement('button');
                viewDescBtn.className = 'btn btn-outline-info btn-sm';
                viewDescBtn.innerHTML = '<i class="bi bi-info-circle"></i> 描述';
                viewDescBtn.title = '查看描述';
                viewDescBtn.addEventListener('click', () => showDescription(bookmark));
                bookmarkActions.appendChild(viewDescBtn);
                
                // 编辑按钮
                const editBtn = document.createElement('button');
                editBtn.className = 'btn btn-outline-secondary btn-sm';
                editBtn.innerHTML = '<i class="bi bi-pencil"></i> 编辑';
                editBtn.title = '编辑';
                editBtn.addEventListener('click', () => showEditBookmarkModal(bookmark));
                bookmarkActions.appendChild(editBtn);
                
                // 删除按钮
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'btn btn-outline-danger btn-sm';
                deleteBtn.innerHTML = '<i class="bi bi-trash"></i> 删除';
                deleteBtn.title = '删除';
                deleteBtn.addEventListener('click', () => deleteBookmark(bookmark.id));
                bookmarkActions.appendChild(deleteBtn);
                
                // 访问按钮
                const visitBtn = document.createElement('button');
                visitBtn.className = 'btn btn-primary btn-sm';
                visitBtn.innerHTML = '<i class="bi bi-box-arrow-up-right"></i> 访问';
                visitBtn.title = '访问网站';
                visitBtn.addEventListener('click', () => window.open(bookmark.url, '_blank'));
                bookmarkActions.appendChild(visitBtn);
                
                bookmarkContainer.appendChild(bookmarkInfo);
                bookmarkContainer.appendChild(bookmarkActions);
                bookmarksList.appendChild(bookmarkItem);
                
                // 添加分割线（除了最后一个书签项）
                if (bookmarksByCategory[category].indexOf(bookmark) < bookmarksByCategory[category].length - 1) {
                    const divider = document.createElement('hr');
                    divider.className = 'bookmark-divider my-2';
                    bookmarksList.appendChild(divider);
                }
            });
            
            categoryContent.appendChild(bookmarksList);
            categoryDiv.appendChild(categoryContent);
            bookmarksContainer.appendChild(categoryDiv);
        }
    }
    
    // 渲染类别列表
    function renderCategories() {
        categoriesContainer.innerHTML = '';
        
        if (allCategories.length === 0) {
            categoriesContainer.innerHTML = '<p class="text-center">暂无类别</p>';
            return;
        }
        
        const categoryList = document.createElement('div');
        categoryList.className = 'category-list';
        
        allCategories.forEach(category => {
            const categoryBadge = document.createElement('span');
            categoryBadge.className = 'category-badge';
            categoryBadge.textContent = category;
            categoryBadge.addEventListener('click', () => filterByCategory(category));
            categoryList.appendChild(categoryBadge);
        });
        
        categoriesContainer.appendChild(categoryList);
    }
    
    // 更新类别选择框
    function updateCategorySelect() {
        bookmarkCategory.innerHTML = '';
        
        allCategories.forEach(category => {
            const option = document.createElement('option');
            option.value = category;
            option.textContent = category;
            bookmarkCategory.appendChild(option);
        });
    }
    
    // 显示添加书签模态框
    function showAddBookmarkModal() {
        // 重置表单
        bookmarkForm.reset();
        bookmarkId.value = '';
        document.getElementById('bookmark-modal-title').textContent = '添加收藏';
        bookmarkModal.show();
    }
    
    // 显示编辑书签模态框
    function showEditBookmarkModal(bookmark) {
        bookmarkId.value = bookmark.id;
        bookmarkTitle.value = bookmark.title || '';
        bookmarkUrl.value = bookmark.url;
        bookmarkCategory.value = bookmark.category;
        bookmarkDescription.value = bookmark.description || '';
        
        document.getElementById('bookmark-modal-title').textContent = '编辑收藏';
        bookmarkModal.show();
    }
    
    // 显示添加类别模态框
    function showAddCategoryModal() {
        categoryName.value = '';
        categoryModal.show();
    }
    
    // 显示描述信息
    function showDescription(bookmark) {
        descriptionTitle.textContent = bookmark.title || bookmark.url;
        
        // 创建完整的描述内容，包括类别、链接和描述
        let fullContent = '';
        
        // 添加类别信息
        fullContent += `<div class="mb-2"><strong>类别：</strong><span class="badge bg-success">${bookmark.category}</span></div>`;
        
        // 添加链接信息
        fullContent += `<div class="mb-2"><strong>链接：</strong><a href="${bookmark.url}" target="_blank">${bookmark.url}</a></div>`;
        
        // 添加描述信息
        fullContent += `<div class="mb-2"><strong>描述：</strong></div><div>${bookmark.description || '无描述'}</div>`;
        
        // 设置HTML内容
        descriptionContent.innerHTML = fullContent;
        descriptionModal.show();
    }
    
    // 保存书签
    function saveBookmark() {
        // 验证表单
        if (!bookmarkUrl.value) {
            alert('请输入网址');
            return;
        }
        
        const bookmark = {
            title: bookmarkTitle.value,
            url: bookmarkUrl.value,
            category: bookmarkCategory.value,
            description: bookmarkDescription.value
        };
        
        // 判断是新增还是编辑
        const isEdit = bookmarkId.value !== '';
        const url = isEdit ? `/api/bookmarks/update/${bookmarkId.value}` : '/api/bookmarks/add';
        const method = isEdit ? 'PUT' : 'POST';
        
        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(bookmark)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                bookmarkModal.hide();
                loadBookmarks(); // 重新加载书签列表
            } else {
                alert('保存失败: ' + (data.detail || '未知错误'));
            }
        })
        .catch(error => {
            console.error('保存书签失败:', error);
            alert('保存失败，请重试');
        });
    }
    
    // 删除书签
    function deleteBookmark(id) {
        if (!confirm('确定要删除这个收藏吗？')) {
            return;
        }
        
        fetch(`/api/bookmarks/delete/${id}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadBookmarks(); // 重新加载书签列表
            } else {
                alert('删除失败: ' + (data.detail || '未知错误'));
            }
        })
        .catch(error => {
            console.error('删除书签失败:', error);
            alert('删除失败，请重试');
        });
    }
    
    // 保存类别
    function saveCategory() {
        const category = categoryName.value.trim();
        
        if (!category) {
            alert('请输入类别名称');
            return;
        }
        
        fetch('/api/bookmarks/categories/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ category: category })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                categoryModal.hide();
                allCategories = data.categories;
                renderCategories();
                updateCategorySelect();
            } else {
                alert('添加类别失败: ' + (data.detail || '未知错误'));
            }
        })
        .catch(error => {
            console.error('添加类别失败:', error);
            alert('添加类别失败，请重试');
        });
    }
    
    // 按类别筛选
    function filterByCategory(category) {
        const filteredBookmarks = allBookmarks.filter(bookmark => bookmark.category === category);
        renderBookmarks(filteredBookmarks);
        
        // 更新类别标签状态
        const categoryBadges = document.querySelectorAll('.category-badge');
        categoryBadges.forEach(badge => {
            if (badge.textContent === category) {
                badge.classList.add('active');
            } else {
                badge.classList.remove('active');
            }
        });
    }
    
    // 搜索书签
    function searchBookmarks() {
        const searchText = searchInput.value.trim();
        const type = searchType.value;
        
        if (!searchText) {
            renderBookmarks(allBookmarks);
            return;
        }
        
        fetch('/api/bookmarks/search', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ text: searchText, type: type })
        })
        .then(response => response.json())
        .then(data => {
            renderBookmarks(data.bookmarks);
            
            // 重置类别标签状态
            const categoryBadges = document.querySelectorAll('.category-badge');
            categoryBadges.forEach(badge => badge.classList.remove('active'));
        })
        .catch(error => {
            console.error('搜索书签失败:', error);
            alert('搜索失败，请重试');
        });
    }
});